package com.yuwei.security.handler;

import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author: zjw
 * @Description: 匿名用户访问无权限资源时的异常
 *      1. 平台所有的 权限都要跟 角色提前绑定： .antMatchers("/data").hasRole("ADMIN")
 *      2. 当一个用户 没有携带 token 时，访问了 .antMatchers("/data") 配置的/data 接口，被视为：匿名用户 。 此时它访问 /data 就会
 *      触发 CustomizeAuthenticationEntryPoint authenticationEntryPoint; 该类的回调
 * @Date Create in 2019/9/3 21:35
 *
 */
@Component
public class CustomizeAuthenticationEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setContentType("text/json;charset=utf-8");
        httpServletResponse.getWriter().write("您没有携带token，请先登录获取token 或 sessionid");
    }

}

